<template>
  <div class="detail-list" @click="onClick(item)">
    <div class="image">
      <img :src="item.image" mode="widthFix"/>
    </div>
    <div class="text">
      <div class="text-content">
        <div class="title">{{item.name}}</div>
        <div class="content">{{item.describe}}</div>
      </div>
      <div class="choose-btn" :style="chooseIcon"></div>
    </div>
  </div>
</template>

<script>
export default {
  props: {
    item: {
      type: Object,
      default: {},
    },
    canChoose: Boolean,
    // 已选中的项
    chosenItemId: {
      type: Array,
      default: []
    }
  },
  data () {
    return {
      chosen: false,
      icons: {
        check: `${require('static/images/onsale/check.png')}`,
        checked: `${require('static/images/onsale/checked.png')}`,
      }
    }
  },
  computed: {
    chooseIcon () {
      if (this.chosen) {
        return `background-image: url(${this.icons.checked});`
      } else {
        return `background-image: url(${this.icons.check});`
      }
    }
  },
  watch: {
    chosenItemId: {
      handler (newVal) {
        if (newVal.indexOf(this.item.item_id) > -1) {
          this.chosen = true
        } else {
          this.chosen = false
        }
      },
      // 立即执行，不用多写一个mounted
      immediate: true
    },
    /**
     * 当chosenItemId未更新时，切换分类列表时，要及时刷新选中情况
     */
    'item.item_id': {
      handler (newVal) {
        if (this.chosenItemId.indexOf(newVal) > -1) {
          this.chosen = true
        } else {
          this.chosen = false
        }
      },
      // 立即执行，不用多写一个mounted
      immediate: true,
      deep: true
    }
  },
  methods: {
    onClick (item) {
      if (this.chosen) {
        this.chosen = false
      } else {
        if (this.canChoose) {
          this.chosen = true
        }
      }
      const data = {
        item,
        chosen: this.chosen
      }
      this.$emit('onClick', data)
    }
  }
}
</script>

<style lang="less" scoped>
.detail-list {
  display: flex;
  align-items: center;
  margin: 0 48rpx;
  padding: 15rpx 0;
  border-bottom: 3rpx dashed #fff;
  &:last-child {
    border-bottom: 0;
  }
  img {
    display: block;
    width: 70rpx;
  }
  .text {
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 100%;
    padding: 0 16rpx;
    .text-content {
      flex: 1;
    }
    .title {
      font-size: 24rpx;
      color: #3f221a;
    }
    .content {
      font-size: 16rpx;
      color: #3f221a;
    }
    .choose-btn {
      width: 31rpx;
      height: 31rpx;
      background-size: contain;
      background-repeat: no-repeat;
      background-position: center center;
      margin-left: 20rpx;
    }
  }
}
</style>
